package com.genymobile.scrcpy.five.cmd;

import android.text.TextUtils;
import android.util.Log;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class CmdParser {
    private static final String TAG = CmdParser.class.getSimpleName();

    private static final Map<String, ICmd> sPraseMap = new HashMap<>();
    private static final ICmd[] cmdList = new ICmd[] {
            new ContextCmd(),
            new FiveMotionEventCmd(),
            new FiveKeyEventCmd(),
            new SleepCmd()
    };
    static {
        for (ICmd cmd : cmdList) {
            sPraseMap.put(cmd.getCmdName(), cmd);
        }
    }

    private static final Map<String, ContextCmd> mContextCmdMap = new HashMap<>();
    public static ICmd parse(String line) {
        if (TextUtils.isEmpty(line)) {
            Log.e(TAG, "empty line");
            return null;
        }
        String[] tmp = line.split(" ");
        if (tmp.length < 3) {
            Log.e(TAG, "invalid line!" + line);
            return null;
        }

        try {
            int i=0;
            long timestampMs = Long.parseLong(tmp[i++]);
            String cmd = tmp[i++];
            ICmd parser = sPraseMap.get(cmd);
            if (parser == null) {
                Log.e(TAG, "unkown cmd !!! " + line);
                return null;
            }

            ICmd parsedCmd = parser.parse(timestampMs, Arrays.copyOfRange(tmp, i, tmp.length));
            if (parsedCmd instanceof ContextCmd) {
                ContextCmd contextCmd = (ContextCmd) parsedCmd;
                if (contextCmd.name != null) {
                    mContextCmdMap.put(contextCmd.name, contextCmd);
                }
            } else {
                if (parsedCmd != null && parsedCmd.context != null) {
                    ContextCmd contextCmd = mContextCmdMap.get(parsedCmd.context);
                    if (contextCmd != null) {
                        contextCmd.apply(parsedCmd);
                    }
                }
            }
//            System.out.println(parsedCmd + " context=" + (parsedCmd != null ? parsedCmd.context : null));
            return parsedCmd;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
